package com.qfedu.service.impl;

import com.qfedu.bean.Users;
import com.qfedu.dao.UserDao;
import com.qfedu.service.UserService;
import com.qfedu.utils.ByteArrToHexString;
import com.qfedu.utils.Hash;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author:zhengyilong
 * @email:1797344574@qq.com
 * @phone:13479394730
 * @desc:
 * @DateTime:2022/5/15 20:26
 **/
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserDao userDao;

    public Users checkLogin(String name, String password) {
        Users user = userDao.QueryUserByName(name);
        //加密验证
        byte[] hash = Hash.SHA256(password.getBytes());
        password = ByteArrToHexString.getByteArrToHexString(hash);
        if (user == null){
            return null;
        }
        if (user.getPassword().equals(password)) {
            return user;
        }else {
            //如果id为0，那么说明登录失败的原因是密码错误
            user.setId(0);
            return user;
        }
    }

    public String insertUser(Users user) {
        Users QueryUserByName = userDao.QueryUserByName(user.getName());
        if (QueryUserByName != null){
            return "用户已存在";
        }
        int i = userDao.InsertUser(user);
        if (i == 1){
            return "新增用户成功";
        }else {
            return "新增用户失败";
        }
    }

    public String updateAdminUser(Users user, String password) {
        Users QueryUserByName = userDao.QueryUserByName(user.getName());
        if (QueryUserByName == null){
            return "修改失败，用户不存在";
        }
        //密码加密
        byte[] hash = Hash.SHA256(password.getBytes());
        password = ByteArrToHexString.getByteArrToHexString(hash);
        int i = userDao.updatePasswordByNameAndPhone(user, password);
        if (i != 1){
            return "修改失败，手机号码错误";
        }else {
            return "修改成功";
        }
    }
}

